#include "version.h"

#include <stddef.h>

#include "sqlite3.h"

#include "log/log.h"

#include "tags.h"

#define CREATE_SQL "CREATE TABLE IF NOT EXISTS IndexVersion(type LONG PRIMARY KEY, version LONG)"

int version_init(sqlite3* db) {
	sqlite3_stmt* statement = NULL;
	int ret = sqlite3_prepare_v2(db, CREATE_SQL, -1, &statement, 0);

//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "version_init: prepare %d", ret);

	if (ret != SQLITE_OK) {
		return ret;
	}

	ret = sqlite3_step(statement);
//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "version_init: step %d", ret);

	sqlite3_finalize(statement);

	return ret;
}

#define GET_SQL "select version from IndexVersion where type=?"

int version_get(sqlite3* db, long long type, long long* ver) {
	sqlite3_stmt* statement = NULL;
	int ret = sqlite3_prepare_v2(db, GET_SQL, -1, &statement, 0);

//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "version_get: prepare %d", ret);

	if (ret != SQLITE_OK) {
		return ret;
	}

	sqlite3_bind_int64(statement, 1, type);

	ret = sqlite3_step(statement);
//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "version_get: step %d", ret);

	if (ret == SQLITE_ROW) {
		*ver = sqlite3_column_int64(statement, 0);
	}

	sqlite3_finalize(statement);

	if (ret == SQLITE_ROW || ret == SQLITE_DONE) {
		return SQLITE_OK;
	}

	return ret;
}

#define SET_SQL "insert or replace into IndexVersion(type, version) values(?, ?)"

int version_set(sqlite3* db, long long type, long long ver) {
	sqlite3_stmt* statement = NULL;
	int ret = sqlite3_prepare_v2(db, SET_SQL, -1, &statement, 0);

//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "version_set: prepare %d", ret);

	if (ret != SQLITE_OK) {
		return ret;
	}

	sqlite3_bind_int64(statement, 1, type);
	sqlite3_bind_int64(statement, 2, ver);

	ret = sqlite3_step(statement);
//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "version_set: step %d", ret);

	sqlite3_finalize(statement);

	return ret;
}

#define RESET_SQL "delete from IndexVersion where type=?"

int version_reset(sqlite3* db, long long type) {
	sqlite3_stmt* statement = NULL;
	int ret = sqlite3_prepare_v2(db, RESET_SQL, -1, &statement, 0);

//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "version_reset: prepare %d", ret);

	if (ret != SQLITE_OK) {
		return ret;
	}

	sqlite3_bind_int64(statement, 1, type);

	ret = sqlite3_step(statement);
//	log_print(ANDROID_LOG_DEBUG, TAG_NIM_INDEX_OP, "version_reset: step %d", ret);

	sqlite3_finalize(statement);

	return ret;
}
